<template>
  <div class="change-langs-modal">
    <Tools
      :isSubmitAll="isSubmitAll"
      @handleIsSubmitAllChange="handleIsSubmitAllChange"
      :fileList="fileList"
      :isValid="isValid"
      @handleIsShowSubmit="handleIsShowSubmit"
      @handleExcelAdd="handleExcelAdd"
      @handleDownloadAll="handleDownloadAll"
      @handleDownloadNeed="handleDownloadNeed"
      @handleInit="handleInit"
    />
    <el-card class="show-wrapper">
      <PaginationTable
        :columns="langColumns"
        :data="showData"
        :table-height="300"
        :is-show-number="true"
      >
        <el-table-column v-if="!isShowSubmit" width="200" label="操作">
          <template v-slot="{ row }">
            <el-button type="primary">
              {{ $t("COMMON.Update") }}
            </el-button>
            <el-button type="danger" @click="handleRemoveItem(row)">
              {{ $t("COMMON.Delete") }}
            </el-button>
          </template>
        </el-table-column>
      </PaginationTable>
    </el-card>
    <footer class="modal-footer" v-show="isShowSubmit">
      <el-button class="footer-op-btn" @click="handleCancel">
        {{ $t("COMMON.Cancel") }}
      </el-button>
      <el-button class="footer-op-btn" type="primary" @click="handleSubmit">
        {{ $t("COMMON.Save") }}
      </el-button>
    </footer>
  </div>
</template>

<script>
import Tools from "./update-langs-tools";

import { langTotalColumns } from "@/libs/business";
import { setLangFile } from "@/api/lang";
import { MessageBox, Message } from "element-ui";
import excel from "@/libs/export-excel";

export default {
  name: "UpdateLangs",
  components: {
    Tools,
  },
  filters: {},
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    limitRules: {
      type: Object,
      default: () => ({}),
    },
    langColumns: {
      type: Array,
      default() {
        return langTotalColumns;
      },
    },
  },
  data() {
    return {
      originData: [],
      tmpData: [],
      isSubmitAll: false,
      fileList: [],
      // 显示提交的数据/原始数据
      isShowSubmit: false,
    };
  },
  computed: {
    isValid() {
      return true;
    },
    showData() {
      if (this.isShowSubmit) {
        return this.tmpData;
      }
      return this.originData.reduce((prev, current) => {
        const isRepeat = prev.some(
          (item) =>
            item.module === current.module && item.sentence === current.sentence
        );
        if (isRepeat) {
          const item = prev.find((item) =>
            item.sentence.includes(current.sentence)
          );
          item[current.lang] = current.sentenceValue;
        } else {
          prev.push({
            ...current,
            [current.lang]: current.sentenceValue,
          });
        }

        delete prev.sentenceValue;
        delete prev.lang;

        return prev;
      }, []);
    },
  },
  watch: {
    limitRules: {
      immediate: true,
      deep: true,
      handler() {
        // this.initRules();
      },
    },
  },
  mounted() {
    this.handleInit();
  },
  methods: {
    handleInit() {
      this.originData = [...this.data];
    },
    initRules() {},
    handleCancel() {
      this.$emit("handleCancel");
    },
    handleSubmit() {
      const ctx = this;
      MessageBox({
        title: ctx.$t("COMMON.Tip"),
        message: ctx.$t("COMMON.ConfirmUpdate", {
          content: ctx.$t("COMMON.CurrentLang"),
        }),
        showCancelButton: true,
        showConfirmButton: true,
        beforeClose: (action, instance, done) => {
          switch (action) {
            case "confirm":
              this.confirmSubmit();
              done();
              break;
            default:
              done();
              break;
          }
        },
      });
    },
    handleRemoveItem(crtItem) {
      const newData = this.originData.filter(
        (item) =>
          !(
            item.module === crtItem.module && item.sentence === crtItem.sentence
          )
      );
      this.tableData = newData;
    },
    async confirmSubmit() {
      const type = "all",
        data = this.tmpData,
        ctx = this;
      if (type && data) {
        const params = {
          type,
          data,
        };
        setLangFile({
          data: params,
          success(res) {
            if ("code" in res && !res.code) {
              Message.success(
                ctx.$t("COMMON.OpSuccess", {
                  content: ctx.$t("COMMON.Update"),
                })
              );
            } else {
              // res.msg
              Message.error(
                ctx.$t("COMMON.FailReason", {
                  op: ctx.$t("COMMON.Update"),
                  reason: res.msg,
                })
              );
            }
            setTimeout(() => {
              ctx.handleCancel();
            }, 500);
          },
          error(err) {
            throw err;
          },
        });
      }
    },
    /**
     * @param {File} file
     */
    handleExcelAdd(file) {
      const formatList = ["xls", "xlsx"];
      const fileNameSplit = file.name.split("."),
        format = fileNameSplit[fileNameSplit.length - 1];
      if (!formatList.includes(format)) {
        Message.warning(this.$t("EXCEL.FileTypeIllegal"));
        return false;
      }
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);

      reader.onload = (e) => {
        const data = e.target.result;
        const { header, results } = excel.read(data, "utf-8");
        this.setTmpData(results);
        console.log(header);
      };

      return false;
    },

    handleDownloadAll() {
      Message.info(this.$t("COMMON.Download"));
      const totalData = [...this.tmpData, ...this.showData];
      if (!totalData.length) {
        this.$message.warning(this.$t("EXCEL.NotNeedAdd"));
      }

      const params = {
        key: this.langColumns.map((item) => item.prop),
        title: this.langColumns.map((item) => `${item.label}/${item.prop}`),
        data: totalData,
        filename: this.$t("EXCEL.CurrentDisplayLang"),
        autoWidth: true,
      };
      excel.export_array_to_excel(params);
    },
    /**
     * 按需导出数据
     */
    handleDownloadNeed() {
      Message.info("按需导出数据");
      const filterData = this.showData.filter((item) => {
        if (
          !(item["zh-CN"] && item["zh-CN"].length) ||
          !(item["zh-XG"] && item["zh-XG"].length) ||
          !(item["en"] && item["en"].length)
        ) {
          return true;
        }
        return false;
      });
      const params = {
        key: this.langColumns.map((item) => item.prop),
        title: this.langColumns.map((item) => `${item.label}/${item.prop}`),
        data: filterData,
        filename: this.$t("EXCEL.PlusLang"),
        autoWidth: true,
      };
      excel.export_array_to_excel(params);
    },
    /**
     * 设置临时数据
     */
    setTmpData(data) {
      const tmpData = data.map((item) => {
        const newItem = {};
        Object.getOwnPropertyNames(item).map((key) => {
          const newKey = key.split("/")[1];
          if (newKey) {
            newItem[newKey] = item[key];
          }
        });

        return newItem;
      });
      this.$set(this, "tmpData", tmpData);
    },
    handleIsSubmitAllChange(value = false) {
      this.$set(this, "isSubmitAll", value);
    },
    handleIsShowSubmit(newVal) {
      this.isShowSubmit = newVal;
    },
  },
};
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
